from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from userapp.models import *
from cartapp.models import *
from orderapp.models import *
from shop.settings import alipay
# Create your views here.
import datetime as datatime
import uuid

#订单支付
class CheckView(View):
    def get(self,request):
        user = request.session.get('user')
        address = Address.objects.get(isdefault=1)
        cart_list = Cart.objects.filter(user_id=user.id)
        num = 0
        sum = 0
        for cart in cart_list:
            sum =sum + cart.goods_price * cart.number
            num = num+cart.number
        return render(request,'order.html',{'address':address,'cart_list':cart_list,'sum':sum,'num':num})


#支付宝支付
class AlipayView(View):
    def get(self, request):
        user = request.session.get('user')
        carts = Cart.objects.filter(user_id=user.id)
        sum = request.GET.get('sum')
        order_number = datatime.datetime.now().strftime('%Y%m%d%H%M%S')
        order = Order.objects.create(
            sum=sum,  # 修改变量名为 total_sum
            uuid=order_number,
            user_id=user.id,
            status='未支付'
        )
        orderid = order.id
        for cart in carts:
            OrderItem.objects.create(
                # 关联订单
                goods_id=cart.goods_id,
                Order_id=orderid,
                order_img=cart.goods_img,
                order_name=cart.goods_name,
                order_price=cart.goods_price,
                order_count=cart.number
            )

            # 使用单个查询删除所有购物车项
        Cart.objects.filter(user_id=user.id).delete()

        total = sum
        # 导入alipay对象,并调用统一收单下单并支付页面接口
        # 参考文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.page.pay
        # python的uuid模块提供UUID类和函数uuid1(), uuid3(), uuid4(), uuid5() 来生成1, 3, 4, 5各个版本的UUID
        # 1基于时间戳；3基于名字的MD5散列值；4基于随机数；5基于名字的SHA-1散列值

        order_param = alipay.api_alipay_trade_page_pay(
            # 商户订单号
            # 由商家自定义，64个字符以内，仅支持字母、数字、下划线且需保证在商户端不重复。
            out_trade_no=str(uuid.uuid4()),
            # 订单总金额
            total_amount=total,
            # 订单标题
            # 注意：不可使用特殊字符，如 /，=，& 等。
            subject=user.name + '的商品',
            # 回调地址
            return_url='http://127.0.0.1:8000/order/checkbuy/' + str(order.id) + '/'
            # 当支付成功后，支付宝沙箱回调给服务端该url指向的get请求
            # return_url='http://593f047.r1.cpolar.top/goods/login/'
        )

        # 拼接支付地址：支付宝网关 + 订单参数
        pay_url = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?' + order_param

        return JsonResponse({'url': pay_url}, status=200)



#支付回调，获取到支付结果
def Checkbuy(request,orderid=1):
    dingdan = request.GET.dict()
    order_number = dingdan.pop('trade_no')
    if order_number:
        Order.objects.filter(id=orderid).update(status='已支付')
    return HttpResponseRedirect('/user/myorder/')